<template>
  <div class="login-page">
    <!-- 顶部 -->
    <van-nav-bar
      title="注册"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' },
        {pattern : /^[a-zA-Z0-9]{6,12}$/, message: '用户名应为6到12位的字母或数字组合'}]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' },
        {pattern : /^[a-zA-Z0-9]{6,12}$/, message: '密码应为6到12位的字母或数字组合'}]"
      />
      <van-field
        v-model="passwords"
        type="password"
        name="rePassword"
        label="确认密码"
        placeholder="请输入密码"
        :rules="[
          { required: true, message: '请填写确认密码' },
          { pattern: /^[a-zA-Z0-9]{6,12}$/, message: '密码应为6到12位的字母或数字组合'},
          { validator: validatePass, message: '两次输入的密码不一致'}
        ]"
      />
      <div style="margin: 16px">
        <van-button
          block
          type="info"
          native-type="submit"
          style="background-color: rgb(0, 125, 187); border: rgb(0, 125, 187)"
          >注册账号</van-button
        >
      </div>
    </van-form>
    <router-link class="link" to="/login">已有账号，去登陆</router-link>
  </div>
</template>

<script>
import { register } from '@/api/user'
export default {
  name: 'LoginPage',
  data () {
    return {
      username: '',
      password: '',
      passwords: ''
    }
  },
  methods: {
    // 添加返回按钮处理方法
    onClickLeft () {
      this.$router.back()
    },
    // 添加表单提交处理方法
    validatePass () {
      return this.password === this.passwords
    },
    // 添加表单提交处理方法
    async onSubmit (values) {
      // 只提取需要的字段
      const { username, password } = values
      await register({ username, password })
      // 提示
      this.$toast.success('注册成功')
      // 清空表单
      this.username = ''
      this.password = ''
      this.passwords = ''
      // 跳转到登录页面
      this.$router.push('/login')
    }
  }
}
</script>

<style lang="less" scoped>
.link {
  color: rgb(0, 125, 187);
  font-size: 12px;
  padding-right: 20px;
  float: right;
}
</style>
